const url = require("url");
const path = require("path");
const jwt = require("jsonwebtoken");
const fs = require("fs");

module.exports = {
  AuthCheck(whiteList = []) {
    return function (req, resp, next) {
      if (whiteList.includes(url.parse(req.url).pathname)) {
        next();
      } else {
        //黑名单
        try {
          // console.log("query.token:"+req.query.token);
          // console.log("body.token:"+req.body.token);
          // console.log("headers.token:"+req.headers.token);
          // console.log(req.cookies.token);
          // console.log(req.headers.authorization.split(/ /)[1]);

          // 1.get请求的url地址上带token
          // 2.post请求的body地址上带token
          // 3.请求头的headers地址上带token
          // 4.cookie地址上带token
          // 5.authorization地址上带token, "Bearer token值"

          let token = "";
          if (req.query && req.query.token) {
            token = req.query.token;
          }
          if (req.body && req.body.token) {
            token = req.body.token;
          }
          if (req.headers && req.headers.token) {
            token = req.headers.token;
          }
          if (req.cookies && req.cookies.token) {
            token = req.cookies.token;
          }
          if (req.headers.authorization) {
            console.log(req.headers.authorization);
            token = req.headers.authorization.split(/ /)[1];
          }
          let public = fs
            .readFileSync(path.join(__dirname, "../keys/rsa_public_key.pem"))
            .toString();
          jwt.verify(token, public, { algorithm: "RS256" }, (err) => {
            if (err) {
              resp.send("您的token失效,请重新登录!");
              return;
            }
            next();
          });
        } catch (error) {
          resp.send("您的未携带token,请先登录!");
          return;
        }
      }
    };
  },
  buildToken(oCurrentInfo = {}, expiresIn = 24 * 60 * 60) {
    let private = fs.readFileSync(
      path.join(__dirname, "../keys/rsa_private_key.pem")
    );
    let token = jwt.sign(oCurrentInfo, private.toString(), {
      expiresIn,
      algorithm: "RS256",
    });
    return token;
  },
};
